package cn.wolfcode.rbac.web.interceptor;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.util.RequriedPermission;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是管理员
        System.out.println("拦截器执行2...拦截权限");
        Employee currentUser = UserContext.getCurrentUser();
        if (currentUser.isAdmin()) {
            return true;
        }
        //处理表达式注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //通过反射获取注解类中的方法或属性等信息
            RequriedPermission annotation = (RequriedPermission) handlerMethod.getMethodAnnotation(RequriedPermission.class);
            if (annotation == null) {
                return true;
            }
            //获取类名，simpleName是获取名字不带包名，name是带包名的
            String simpleName = handlerMethod.getBean().getClass().getSimpleName().replace("Controller", "");
            //大写字母变小写，得到方法名字
            String expression = StringUtils.uncapitalize(simpleName) + ":" + handlerMethod.getMethod().getName();
            //获取到SESSION中的EXPERSSION_IN_SESSION值
            List<String> permission = UserContext.getExpression();
            if (permission.contains(expression)) {
                return true;
            }
        }
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request, response);
        return false;
    }
}
